/**
 * 剑指 Offer 57 - II. 和为s的连续正数序列
 * https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/
 */
const { displayNestedArray } = require('../../libs/public');

/**
 * @param {number} target
 * @return {number[][]}
 */
function findContinuousSequence(target) {
  const end = target % 2 === 1 ? Math.ceil(target / 2) : (target / 2);
  const queue = new Array(end + 1).fill(0);
  for (let i = 1; i <= end; i += 1) {
    queue[i] = i;
  }
  const result = [];
  let sum = 1;
  let left = 1;
  let right = 1;
  while (right <= end) {
    if (sum === target) {
      if (left < right) {
        result.push(queue.slice(left, right + 1));
      }
      right += 1;
      sum += right;
    } else if (sum < target) {
      right += 1;
      sum += right;
    } else {
      sum -= left;
      left += 1;
    }
  }
  return result;
}

console.log(displayNestedArray(findContinuousSequence(1)) === '[]');
console.log(displayNestedArray(findContinuousSequence(2)) === '[]');
console.log(displayNestedArray(findContinuousSequence(3)) === '[[1,2]]');
console.log(displayNestedArray(findContinuousSequence(9)) === '[[2,3,4],[4,5]]');
console.log(displayNestedArray(findContinuousSequence(15)) === '[[1,2,3,4,5],[4,5,6],[7,8]]');
